﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LootPoints.Security;

namespace LootPoints.Pages
{
    public partial class ResetTool : Page
    {
        string resetCode;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            try { if ((bool)Session["logged"] == true) Response.Redirect("~/Pages/Overview.aspx"); }
            catch { /* User isnt logged in, stay on page */ }

            try { resetCode = Request.QueryString[0].ToString(); }
            catch { Response.Redirect("~/Default.aspx"); }

            if (IsPostBack) { lblUsername.Text = ""; lblStatus.Text = ""; }
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                ModelContainer context = new ModelContainer();
                Character character = (from c in context.Character where c.Name == tbUsername.Text && c.Reset == true select c).FirstOrDefault();
                if (character != null)
                {
                    if (Hashing.ValidatePassword(resetCode, character.ResetCode))
                    {
                        character.Password = Hashing.CreateHash(tbRpassword.Text);
                        character.Reset = false;
                        character.ResetCode = "";
                        context.SaveChanges();
                        mpeAdd.Show();
                    }
                    else { lblUsername.Text = "*"; lblStatus.Text = "The reset session cannot be verified."; }
                }
                else { lblUsername.Text = "*"; lblStatus.Text = "Character not found or is not flagged for password reset."; }
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Pages/Login.aspx");
        }
    }
}